<template>
  <view class="bank">
    <view class="bank-box">
      <u-form :model="form" ref="uForm" :label-width="152">
        <u-form-item
          ref="phone"
          prop="phone"
          label="手机号码"
          class="form-item-box"
          required
        >
          <u-input
            :disabled="true"
            v-model="form.phone"
            placeholder="请输入手机号码"
          />
        </u-form-item>
        <u-form-item
          ref="verificationCode"
          prop="verificationCode"
          label="验证码"
          class="form-item-box"
          required
        >
          <u-input
            type="number"
            v-model="form.verificationCode"
            placeholder="请输入验证码"
          />
          <view class="code" :class="{ disabled: timer }" @click="sendCode">
            {{ codeText }}
          </view>
        </u-form-item>
        <u-form-item
          v-if="userInfo.operatePwdFlag == '1'"
          ref="oldOperatePassword"
          prop="oldOperatePassword"
          label="旧密码"
          class="form-item-box"
          required
        >
          <u-input
            @click="handleShowKeyboard(0)"
            :disabled="true"
            type="password"
            :maxlength="6"
            v-model="form.oldOperatePassword"
            placeholder="请输入旧密码"
          />
        </u-form-item>
        <u-form-item
          ref="operatePassword"
          prop="operatePassword"
          label="账户密码"
          class="form-item-box"
          required
        >
          <u-input
            :disabled="true"
            type="password"
            :maxlength="6"
            v-model="form.operatePassword"
            @click="handleShowKeyboard(1)"
            placeholder="请输入6位密码"
          />
        </u-form-item>
        <u-form-item
          ref="operatePassword1"
          prop="operatePassword1"
          label="确认密码"
          class="form-item-box"
          required
        >
          <u-input
            :disabled="true"
            @click="handleShowKeyboard(2)"
            type="password"
            :maxlength="6"
            v-model="form.operatePassword1"
            placeholder="请再次输入密码"
          />
        </u-form-item>
      </u-form>
    </view>
    <u-keyboard
      mode="number"
      @change="keyboardChange"
      :dot-enabled="false"
      :tooltip="false"
      :mask="false"
      :safe-area-inset-bottom="true"
      @backspace="keyboardBackspace"
      v-model="showKeyboard"
    ></u-keyboard>
    <u-keyboard
      mode="card"
      @change="keyboardChange1"
      :dot-enabled="false"
      :tooltip="false"
      :mask="false"
      :safe-area-inset-bottom="true"
      @backspace="keyboardBackspace1"
      v-model="showKeyboard1"
    ></u-keyboard>
    <view class="submit-btn" @click="handleSubmit">确定</view>
    <view class="alert">温馨提示：密码设置建议不要使用连续或重复数字</view>
    <AlertModal
      :showModal="showModal"
      desc="密码设置成功"
      mode="2"
      @confirm="handleConfirm"
      :showCancel="false"
    />
  </view>
</template>
<script>
import AlertModal from './Modal.vue'

export default {
  components: {
    AlertModal,
  },
  data() {
    // 密码验证
    const pwdCheck = async (rule, value, callback) => {
      let reg = /^\d{6}$/
      if (!value) {
        return callback(new Error('新密码不能为空'))
      } else if (value.length < 6) {
        return callback(new Error('新密码不能少于6位'))
      } else if (value.length > 6) {
        return callback(new Error('新密码最长不能超过6位'))
      } else if (!reg.test(value)) {
        return callback(new Error('密码应为6位数字，请检查格式是否正确！'))
      } else {
        callback()
      }
    }
    // 重复密码验证
    const pwdAgainCheck = async (rule, value, callback) => {
      if (!value) {
        return callback(new Error('再次输入新密码不能为空'))
      } else if (this.form.operatePassword != this.form.operatePassword1) {
        return callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      showKeyboard: false,
      showModal: false,
      form: {
        operatePassword: '',
        operatePassword1: '',
        oldOperatePassword: '',
        idCardNo: '',
      },
      timer: null,
      time: 60,
      rules: {
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['change', 'blur'],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          },
        ],
        verificationCode: [
          {
            required: true,
            message: '请输入验证码',
            trigger: ['change', 'blur'],
          },
        ],
        operatePassword: [
          {
            required: true,
            validator: pwdCheck,
            trigger: ['change', 'blur'],
          },
        ],
        oldOperatePassword: [
          {
            required: true,
            validator: pwdCheck,
            trigger: ['change', 'blur'],
          },
        ],
        operatePassword1: [
          {
            required: true,
            validator: pwdAgainCheck,
            trigger: ['change', 'blur'],
          },
        ],
      },
      userInfo: {},
      currentInput: 0,
      showKeyboard: false,
      showKeyboard1: false,
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  onShow() {
    this.getuserInfo()
  },
  computed: {
    codeText() {
      if (!this.timer) {
        return '获取验证码'
      } else {
        return `${this.time}s后重新获取`
      }
    },
  },
  methods: {
    //触发校验
    triggerSingleFieldValidate(refName) {
      this.$refs[refName].onFieldChange()
    },
    handleShowKeyboard(type) {
      this.currentInput = type
      this.showKeyboard = true
    },
    keyboardChange(e) {
      switch (this.currentInput) {
        case 0:
          if (this.form.oldOperatePassword.length < 6) {
            this.form.oldOperatePassword =
              this.form.oldOperatePassword + (e + '')
            this.triggerSingleFieldValidate('oldOperatePassword')
          }
          break
        case 1:
          if (this.form.operatePassword.length < 6) {
            this.form.operatePassword = this.form.operatePassword + (e + '')
            this.triggerSingleFieldValidate('operatePassword')
          }
          break
        case 2:
          if (this.form.operatePassword1.length < 6) {
            this.form.operatePassword1 = this.form.operatePassword1 + (e + '')
            this.triggerSingleFieldValidate('operatePassword1')
          }
          break
        default:
          break
      }
    },
    keyboardChange1(e) {
      if (this.form.idCardNo.length < 18) {
        this.form.idCardNo = this.form.idCardNo + e
        this.triggerSingleFieldValidate('idCardNo')
      }
    },
    keyboardBackspace1() {
      if (this.form.idCardNo.length && this.form.idCardNo.length <= 18) {
        this.form.idCardNo = this.form.idCardNo.slice(
          0,
          this.form.idCardNo.length - 1
        )
        this.triggerSingleFieldValidate('idCardNo')
      }
    },
    keyboardBackspace() {
      switch (this.currentInput) {
        case 0:
          if (
            this.form.oldOperatePassword.length &&
            this.form.oldOperatePassword.length <= 6
          ) {
            this.form.oldOperatePassword = this.form.oldOperatePassword.slice(
              0,
              this.form.oldOperatePassword.length - 1
            )
            this.triggerSingleFieldValidate('oldOperatePassword')
          }
          break
        case 1:
          if (
            this.form.operatePassword.length &&
            this.form.operatePassword.length <= 6
          ) {
            this.form.operatePassword = this.form.operatePassword.slice(
              0,
              this.form.operatePassword.length - 1
            )
            this.triggerSingleFieldValidate('operatePassword')
          }
          break
        case 2:
          if (
            this.form.operatePassword1.length &&
            this.form.operatePassword1.length <= 6
          ) {
            this.form.operatePassword1 = this.form.operatePassword1.slice(
              0,
              this.form.operatePassword1.length - 1
            )
            this.triggerSingleFieldValidate('operatePassword1')
          }
          break
        default:
          break
      }
    },
    async getuserInfo() {
      const res = await this.$u.get('/freight-business/get/userInfo')
      if (res.code === '0') {
        uni.setStorageSync('userInfo', res.result)
        this.userInfo = res.result
        uni.setNavigationBarTitle({
          title: `${
            res.result.operatePwdFlag == '0' ? '设置' : '修改'
          }账户密码`,
        })
        this.form.accountId = this.userInfo.accountId
        this.form.phone = this.userInfo.phone
      } else {
        this.$api.msg(res.message)
      }
    },
    // 发送短信验证码
    async getCodeData(val) {
      const { code, result, message } = await this.$u.post(
        '/freight-auth/client/smsSend',
        val
      )
      if (code === '0') {
        this.$api.msg('短信验证已发送')
      } else {
        this.$api.msg(message)
      }
    },
    handleConfirm() {
      this.showModal = false
      uni.navigateBack()
    },
    sendCode() {
      if (this.timer) return
      if (this.form.phone) {
        this.timer = setInterval(() => {
          this.time--
          if (this.time < 1) {
            clearInterval(this.timer)
            this.timer = null
            this.time = 60
          }
        }, 1000)
        this.getCodeData({
          type: '1',
          iphone: this.form.phone,
        })
      } else {
        this.$api.msg('请先输入手机号码')
      }
    },
    handleSubmit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.submitData(this.form)
        } else {
          this.$api.msg('请填写相关信息')
        }
      })
    },
    async submitData(val) {
      const { code, result, message } = await this.$u.post(
        '/freight-auth/userAccount/setOperatePassword',
        val
      )
      if (code === '0') {
        this.showModal = true
      } else {
        this.$api.msg(message)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.bank {
  min-height: 100vh;
  background: #f6f6f6;
  padding: 30rpx;
  box-sizing: border-box;
  &-box {
    width: 690rpx;
    background: #ffffff;
    border-radius: 10rpx;
    padding: 0 24rpx;
    box-sizing: border-box;
  }
}
.code {
  width: 140rpx;
  height: 48rpx;
  background: #387cf9;
  border-radius: 8rpx;
  text-align: center;
  line-height: 48rpx;
  color: #fff;
  font-size: 24rpx;
  font-weight: 500;
  color: #ffffff;
  &.disabled {
    background: #eee;
    width: 180rpx;
  }
}
.submit-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 80rpx;
  width: 690rpx;
  height: 80rpx;
  margin: 0 auto;
  background: #378afb;
  border-radius: 10rpx;
  text-align: center;
  line-height: 80rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  color: #ffffff;
}
.alert {
  font-size: 28rpx;
  color: #f97825;
  line-height: 40rpx;
  margin-top: 24rpx;
}
</style>
